package no.ntnu.fp.handlers;

import java.io.IOException;

import no.ntnu.fp.connection.ReceiveWorker;
import no.ntnu.fp.handler.Handler;
import no.ntnu.fp.handlers.exceptions.NetworkException;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.impl.NoticeReadMessage;
import no.ntnu.fp.messages.impl.NoticeAddedOrUpdatedMessage;
import no.ntnu.fp.model.Notice;
import no.ntnu.fp.net.co.Connection;
import no.ntnu.fp.services.NoticeService;

public class NoticeReadHandler implements Handler {

	private final NoticeService noticeService;
	
	public NoticeReadHandler(NoticeService noticeService) {
		this.noticeService = noticeService;
	}

	@Override
	public void handleMessage(Message message) {
		NoticeReadMessage noticeReadMessage = (NoticeReadMessage) message;
		
		Notice notice = noticeReadMessage.getNotice();
		notice = noticeService.markAsRead(notice);
		
		Message reply = new NoticeAddedOrUpdatedMessage(notice, 
														notice.getEmployee());
		
		Connection connection = ReceiveWorker.getThreadLocalConnection();
		try {
			connection.send(reply.toString());
		} catch (IOException ex) {
			throw new NetworkException("Unable to send reply " + reply, ex);
		}
		
	}
}
